from flask import Blueprint, jsonify, request
from db import db1
from utils.comm import get_data
import json
from qiniu import Auth
# from flask.ext.mail import Mail, Message
import os
bp_cbf = Blueprint('cflask', __name__)


##################################################
# 七牛云
access_key = 'mIdF1uL0g-chyQDrdJuWYZTqrWgsNJleEzMaxZ3o'
secret_key = 'G8dj2qEqTQUJT9p_X_xusFXhpP9mFnDNArpGI41i'

@bp_cbf.route('/qntoken')
def qntoken():
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'p7cbf'
    # 生成上传 Token
    token = q.upload_token(bucket_name)
    return jsonify({"token":token})
#################################################

@bp_cbf.route('/yw', methods=['POST', 'GET'])
def yw():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = """insert into yw values (%d,'%s','%s')""" % (0, data['name'], '')
        db1.insert(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        sql = """select * from yw"""
        list = db1.find_all(sql)
        return jsonify({'code': 200, "list": list})


@bp_cbf.route('/setparams', methods=['POST', 'GET'])
def setparams():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "update yw set canshu='%s' where id=%d" % (data['canshu'], int(data['id']))
        db1.insert(sql)
        return jsonify({"code": 200})
    elif request.method == 'GET':
        wid = request.args.get('wid')
        sql = """select * from yw where id=%d""" % (int(wid))
        res = db1.find_one(sql)
        return jsonify({'code': 200, "list": res})


@bp_cbf.route('/yhlM', methods=['POST', 'GET'])
def yhlM():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = """insert into yhl values (%d,'%d','%d','%s')""" % (0, int(data['uid']), int(data['wid']), data['pamars'])
        db1.insert(sql)
        return jsonify({'code': 200})


###########################################################

def xtree(data):
    list = []
    tree = {}
    if not data:
        return data
    for i in data:
        tree[i['id']] = i
    for j in data:
        pid = j['pid']
        if pid == 0:
            list.append(j)
        else:
            # 查看父类下有没有子类
            if 'son' not in tree[pid]:
                # 如果没有初始化列表
                tree[pid]['son'] = []
            # 把子类加到父类列表中
            tree[pid]['son'].append(j)
    return list


@bp_cbf.route('/cateM', methods=['POST', 'GET'])
def cateM():
    if request.method == 'POST':
        data = get_data()
        sql = """insert into cates values(0,'%s',%d,%s)""" % (data['name'], int(data['pid']), data['params'])
        db1.insert(sql)
        return jsonify({'code': 200})

    elif request.method == 'GET':
        sql = """select * from  cates"""
        res = db1.find_all(sql)
        data = xtree(res)
        return jsonify({'code': 200, "list": data})


import time


@bp_cbf.route('/teaM', methods=['POST', 'GET'])
def teaM():
    if request.method == 'GET':
        time.sleep(0.1)
        sql = """select * from teacher"""
        res = db1.find_all(sql)
        return jsonify({"code": 200, "list": res})


@bp_cbf.route('/getCateByid')
def getCateByid():
    id = request.args.get('id')
    sql = "select params from cates where id=%d" % (int(id))
    res = db1.find_one(sql)
    return jsonify({'code': 200, 'params': res['params']})


@bp_cbf.route('/courseM', methods=['POST', 'GET'])
def courseM():
    data = get_data()
    if data['params']:
        sql = "insert into courses values(0,'%s',%d,'%s','%s','%s',%d,%d)" % (
            data['title'], int(data['pid']), data['params'], data['pic'], data['descrip'], int(data['teacher_id']),
            int(data['status']))
    else:
        sql = "insert into courses(title,pid,pic,descrip,teacher_id,status) values('%s',%d,'%s','%s',%d,%d)" % (
            data['title'], int(data['pid']), data['pic'], data['descrip'], int(data['teacher_id']), int(data['status']))

    db1.insert(sql)
    return jsonify({"code": 200})


@bp_cbf.route('/pageM', methods=['POST', 'GET'])
def pageM():
    if request.method == 'GET':
        cpage = request.args.get('cpage')
        page_size = 2
        start = (int(cpage) - 1) * page_size
        sql = "select c.id,c.title,c.pic,ca.name from courses as c left join cates as ca on c.pid=ca.id limit %d,%d"%(start,page_size)
        res = db1.find_all(sql)
        sql1 = """select count(id) as count from  courses"""
        total = db1.find_one(sql1)
        return jsonify({"code": 200,"list":res,"total":total['count']})
#获取课程
@bp_cbf.route('/get_courses')
def get_courses():
    sql = """select * from courses """
    res = db1.find_all(sql)
    print(res)
    return jsonify({"code":200,"list":res})



@bp_cbf.route('/vedioUpload',methods=['POST'])
def vedioUpload():
    if request.method == 'POST':
    # 获取要上传的文件流，课程id
        file = request.files['file']
        courses_id = request.form['courses_id']
        path = "./static/upload/"+str(courses_id)
        if not os.path.exists(path):
            os.mkdir(path)
            # 上传文件到指定文件夹
            file.save(os.path.join(path, file.filename))
            # 返回结果
            return jsonify({"code": 200, 'url': path + '/' + file.filename})

#添加章节接口
@bp_cbf.route('/jieM',methods=['POST','GET'])
def jieM():
    if request.method == "POST":
        data = get_data()
        sql = "insert into jie values(0,'%s',%d,'%s')"%(data['name'],int(data['courses_id']),data['vedio_url'])
        db1.insert(sql)
        return jsonify({"code":200})
    else:
        # # #获取章节列表必须传入课程id
        courses_id = request.args.get('id')
        if not courses_id:
            return jsonify({"code":10010,'mes':'必须传入课程id才能获取章节信息'})
        sql = """select j.id,j.name,j.video_url,c.title from jie as j left join courses as c on j.courses_id=c.id where courses_id = %d"""%int(courses_id)
        res = db1.find_all(sql)
        return jsonify({"code":200,'list':res})








